package com.hyacinth.queue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 队列线程类
 * 子类需要实现三个方法，才能使用该队列
 * 1、{@link #setRun(boolean)} 设置运行状态
 * 2、{@link #isRunning()} 判断运行状态
 * 3、{@link #execute()} 真正的处理流程
 * @author zhangfb
 * @version 1.0.0.1
 */
public abstract class QueueThread extends Thread {
	
	protected static final Logger logger = LoggerFactory.getLogger(QueueThread.class);

	// need child class implement run status
	protected abstract boolean isRunning();

	// need child class set run status
	protected abstract void setRun(boolean running);
	
	private synchronized boolean startRun() {
		if (isRunning()) {
			logger.error("QueueThread is runing!!!");
			return false;
		}
		setRun(true);
		return true;
	}
	
	private synchronized boolean stopRun() {
		setRun(false);
		return true;
	}

	// child class implement real handler
	protected abstract void execute();

	@Override
	public void run() {
		if (!startRun()) {
			return;
		}
		try {
			execute();
		} catch (Exception e) {
			logger.error("QueueThread run error!!!", e);
		} finally {
			stopRun();
		}
	}

}
